package mearth;
import java.io.Serializable;

import processing.core.PApplet;
import processing.core.PImage;


public class GridImage implements Serializable {
	
	private Palette palette = new Palette(127);
	
	private GridNode root = null;
	
	private int w = 0;
	private int h = 0;
	
	public GridImage(PApplet app, String fname){
		PImage img = app.loadImage(fname);
		if(img != null){
			palette = new Palette(127);
			w = img.width;
			h = img.height;
			img.loadPixels();
			root = new GridNode().partition(0,  0,  w,  h,  img.pixels, w, palette);
		}
		img = null;
		System.gc();
	}
	
	public GridImage(PApplet app, PImage img){
		if(img != null){
			palette = new Palette(127);
			w = img.width;
			h = img.height;
			img.loadPixels();
			root = new GridNode().partition(0,  0,  w,  h,  img.pixels, w, palette);
		}
	}
	
	public void display(PApplet app, int mx, int my, int mw, int mh){
		NodeInfo info = root.smallestFit(0, 0, w, h, mx, my, mw, mh);
		
		info.node.display(app, info.mx, info.my, info.mw, info.mh, palette);
	}

	public void display(PApplet app){
		root.display(app, 0, 0, w, h, palette);
	}

	public static class Palette implements Serializable {
		int[] colors;
		int nbrColors;
		
		public Palette(int size){
			colors = new int[size];
			nbrColors = 0;
		}
		
		public byte addColor(int col){
			for(int i = 0; i < nbrColors; i++){
				if(colors[i] == col)
					return (byte) i;
			}
			colors[nbrColors++] = col;
			return (byte) nbrColors;
		}
		
		public int getColor(byte idx){
			return colors[idx];
		}
		
	}
}
